﻿using System;
using System.Collections.Generic;
using System.Text;
using ProxyHero.Common;
using System.Windows.Forms;

namespace ProxyHero.HttpUility
{
    //验证用线程1断点续传下载网络上的文件到本地电脑
    public class DownloadHelper
    {
        //打开上次下载的文件或新建文件 
        public string StrUrl;//文件下载网址
        public string StrFileName;//下载文件保存地址 
        public string ErrorInfo;//返回结果
        public long lStartPos = 0; //返回上次下载字节
        public long lCurrentPos = 0;//返回当前下载字节
        public long lDownloadFile;//返回当前下载文件长度
        private string configIniPath = Config.ProxyHeroPath + @"\config.ini";
        public IniHelper iniHelper;

        public DownloadHelper()
        {
            iniHelper = new IniHelper(configIniPath);
        }

        public void DownloadFile()
        {
            System.IO.FileStream fs;
            if (System.IO.File.Exists(StrFileName))
            {
                fs = System.IO.File.OpenWrite(StrFileName);
                lStartPos = fs.Length;
                fs.Seek(lStartPos, System.IO.SeekOrigin.Current);
                //移动文件流中的当前指针 
            }
            else
            {
                fs = new System.IO.FileStream(StrFileName, System.IO.FileMode.Create);
                lStartPos = 0;
            }

            //打开网络连接 
            try
            {
                System.Net.HttpWebRequest request = (System.Net.HttpWebRequest)System.Net.HttpWebRequest.Create(StrUrl);
                request.Proxy = null;
                long length = request.GetResponse().ContentLength;
                lDownloadFile = length;
                if (lStartPos > 0)
                    request.AddRange((int)lStartPos); //设置Range值 

                //向服务器请求，获得服务器回应数据流 
                System.IO.Stream ns = request.GetResponse().GetResponseStream();

                byte[] nbytes = new byte[512];
                int nReadSize = 0;
                nReadSize = ns.Read(nbytes, 0, 512);
                while (nReadSize > 0)
                {
                    fs.Write(nbytes, 0, nReadSize);
                    nReadSize = ns.Read(nbytes, 0, 512);
                    lCurrentPos = fs.Length;
                }

                fs.Close();
                ns.Close();
                ErrorInfo = string.Empty;
                iniHelper.write("updateini", "today", DateTime.Now.ToString());
            }
            catch (System.Net.WebException)
            {
                ErrorInfo = "下载过程中出现错误，请检查网络设置是否正确！";
            }
            catch (Exception ex)
            {
                fs.Close();
                ErrorInfo = "下载过程中出现错误：" + ex.ToString();
            }

        }
    }
    //定义下载类结束 

}
